<!-- 全局播放器 -->
<template>
  <!--  v-show="currentPlayList.length > 0" -->
  <div class="player" v-show="currentPlayList.length > 0">
    <!-- mini -->
    <mini-player
      :show="miniPlayer"
      :style="miniStyle"
      @togglePlayState="togglePlayState"
      @toggleMenuShow="handleActionSheet"
    ></mini-player>
    <transition name="normal">
      <!-- full -->
      <full-player
        :show="fullPlayer"
        @togglePlayState="togglePlayState"
        @changePlayMode="changePlayMode"
        @playPrevSong="playPrevSong"
        @playNextSong="playNextSong"
        @toggleMenuShow="handleActionSheet"
        @changePlayTime="changePlayTime"
      ></full-player>
    </transition>
    <!-- audio -->
    <audio
      ref="audioRef"
      @canplay="audioCanPlay"
      @error="audioError"
      @timeupdate="audioTimeUpdate"
      @ended="audioEnded"
    ></audio>
  </div>

  <!-- 播放列表 -->
  <van-action-sheet v-model:show="actionSheetShow">
    <van-cell>
      <template #title>
        <span @click="changePlayMode">
          <van-icon v-if="currentPlayMode === 0" class-prefix="my-icon" name="loop">顺序播放</van-icon>
          <van-icon v-if="currentPlayMode === 1" class-prefix="my-icon" name="singlecycle">循环播放</van-icon>
          <van-icon v-if="currentPlayMode === 2" class-prefix="my-icon" name="random">随机播放</van-icon>
          ({{ currentPlayList.length }}首)
        </span>
      </template>
    </van-cell>
    <song-list
      :songs="currentPlayList"
      layout="1"
      @handleItemClick="handleItemClick"
      @handleActionDel="handleActionDel"
    ></song-list>
    <van-cell></van-cell>
  </van-action-sheet>
</template>

<script lang="ts" setup>
import { ref, watch, nextTick } from 'vue';
// components
import MiniPlayer from './components/mini-player/MiniPlayer.vue';
import FullPlayer from './components/full-player/FullPlayer.vue';
import SongList from '../songlist/SongList.vue';

// 歌词解析
import Lyric from '@/assets/js/lyric';
import { transferTime } from '@/assets/js/util';
import { getSongLyric } from '@/api/wangyi/song';
import { shuffle } from '@/assets/js/util';

// stores
import { useMyStores } from '@/store';

defineProps({
  miniStyle: {
    type: Object,
    default: {}
  }
});

// 播放模式
enum PlayMode {
  sequence = 0, //顺序播放
  loop = 1, // 循环播放
  random = 2 // 随机播放
}

const {
  playerStore,
  miniPlayer,
  fullPlayer,
  audioReady,
  audioPlayState,
  currentPlayList,
  currentPlayIndex,
  currentPlaySong,
  currentPlayMode,
  sequenceList
} = useMyStores();

/**
 * 处理audio
 */
const audioRef = ref<any>();
const audioCanPlay = (e: any) => {
  playerStore.SET_AUDIO_READY(true);
  // 记录当前播放歌曲
  playerStore.SET_CURRENT_PLAY_HISTORY(currentPlaySong.value);
  // 记录歌曲区时间
  playerStore.SET_AUDIO_TOTAL_TIME(e.target.duration);
};
const audioError = () => {
  console.log('当前歌曲加载失败，已自动为您切换下一首.');
  playerStore.SET_AUDIO_READY(true);
  setTimeout(() => {
    playNextSong();
  }, 1000);
};
const audioTimeUpdate = (e: any) => {
  playerStore.SET_AUDIO_PLAY_TIME(e.target.currentTime);
};
const audioEnded = () => {
  currentPlayMode.value == PlayMode.loop ? playLoopSong() : playNextSong();
};
// 更新播放时间与歌词进度
const changePlayTime = (val: number) => {
  audioRef.value.currentTime = val;
  if (lyricParserRef.value) {
    // lyricParserRef.value.seek(val * 1000);
    lyricParserRef.value.seek(transferTime(val))
  }
};

/**
 * 处理播放
 */
// 切换播放状态
const togglePlayState = () => {
  // 停止/播放当前歌词播放
  if (lyricParserRef.value) {
    lyricParserRef.value.togglePlay();
  }
  playerStore.SET_AUDIO_PLAY_STATE(!audioPlayState.value);
};
const playPrevSong = () => {
  if (!audioReady.value) {
    return;
  }
  if (currentPlayList.value.length === 1) {
    playLoopSong();
  } else {
    let index = currentPlayIndex.value - 1;
    if (index === -1) {
      index = currentPlayList.value.length - 1;
    }
    playerStore.SET_CURRENT_PLAY_INDEX(index);
    playerStore.SET_AUDIO_PLAY_STATE(true);
  }
  playerStore.SET_AUDIO_READY(false);
};
const playLoopSong = () => {
  // 单曲循环播放结束歌词回到初始位置
  if (lyricParserRef.value) {
    lyricParserRef.value.seek(0);
  }
  audioRef.value.currentTime = 0;
  audioRef.value.play();
};
// 播放器播放完毕根据播放模式切歌
const playNextSong = () => {
  if (!audioReady.value) {
    return;
  }
  if (currentPlayList.value.length === 1) {
    playLoopSong();
  } else {
    let index = currentPlayIndex.value + 1;
    if (index === currentPlayList.value.length) {
      index = 0;
    }
    playerStore.SET_CURRENT_PLAY_INDEX(index);
    playerStore.SET_AUDIO_PLAY_STATE(true);
  }
  playerStore.SET_AUDIO_READY(false);
};
// 改变播放模式
const changePlayMode = () => {
  const mode = (currentPlayMode.value + 1) % 3;
  playerStore.SET_CURRENT_PLAY_MODE(mode);
  let list: Array<any> = [];
  if (mode === PlayMode.random) {
    list = shuffle(sequenceList.value);
  } else {
    list = sequenceList.value;
  }
  let index = list.findIndex(item => item.id === currentPlaySong.value.id);
  playerStore.SET_CURRENT_PLAY_INDEX(index);
  playerStore.SET_CURRENT_PLAY_LIST(list);
};

// 处理歌词
const lyricParserRef = ref<any>();
// 获取歌词
const _getSongLyric = (id: number | string) => {
  getSongLyric(id)
    .then(res => {
      console.log('Lyric: ', res);
      const { lyric } = res.lrc;
      // console.log('Lyric: ', lyric);
      // lyricParserRef.value = new LyricParser(lyric, handleLyric);
      lyricParserRef.value = new Lyric(lyric, handleLyric);
      playerStore.SET_LYRIC(lyricParserRef.value);
      if (audioPlayState.value) {
        lyricParserRef.value.play();
      }
    })
    .catch(() => {
      console.log('player组件 Lyric请求错误');
      lyricParserRef.value = null;
      playerStore.SET_LYRIC(lyricParserRef.value);
      playerStore.SET_LYRIC_INDEX(0);
      playerStore.SET_LYRIC_INDEX_TXT('');
    });
};
const handleLyric = ({ lineNum, txt }: any) => {
  playerStore.SET_LYRIC_INDEX(lineNum);
  playerStore.SET_LYRIC_INDEX_TXT(txt);
};

// 检测播放状态
watch(audioPlayState, newVal => {
  nextTick(() => {
    newVal ? audioRef.value.play() : audioRef.value.pause();
  });
});
// 检测歌曲变化
watch(currentPlaySong, (newVal, oldVal) => {
  // 当清空播放列表时，newSong为空，跳过下面操作
  if (!newVal.id) return;
  // 当是同一首歌曲时，不进行下面的操作
  if (newVal.id === oldVal.id) return;
  // 清除当前歌词自动跳转计时
  if (lyricParserRef.value) {
    lyricParserRef.value.stop();
  }
  // 播放音乐
  nextTick(() => {
    // 获取歌词
    _getSongLyric(newVal.id);
    // 播放音乐
    audioRef.value.src = newVal.url;
    audioRef.value.play();
  });
});

// 动作面板,处理菜单开关
const actionSheetShow = ref<boolean>(false);
const handleActionSheet = () => {
  actionSheetShow.value = true;
};
const handleItemClick = (index: number) => {
  // 改变播放索引
  playerStore.SET_CURRENT_PLAY_INDEX(index);
  // 改变播放状态
  playerStore.SET_AUDIO_PLAY_STATE(true);
  actionSheetShow.value = false;
};
const handleActionDel = (index: number) => {
  console.log(index);
};
// 面板头部信息
</script>

<style lang="less" scoped>
.my-icon {
  font-size: 16px;
}
/* 动画 */
.normal-enter-active {
  animation: animate 0.5s;
}
.normal-leave-active {
  animation: animate 0.5s reverse;
}
@keyframes animate {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}
</style>
